#ifndef BUFFER_H
#define BUFFER_H

#include "util.hpp"
#include <vector>
#include <cassert>

namespace Log
{
    #define DEFAULT_BUFFER_SIZE (1 * 1024 * 1024)
    #define THRESHOLD_BUFFER_SIZE (8 * 1024 * 1024)
    #define INCREMENT_BUFFER_SIZE (2 * 1024 * 1024)

    class Buffer
    {
    public:
        Buffer() : _buffer(DEFAULT_BUFFER_SIZE), _reader_idx(0), _writer_idx(0) {}

        // 向缓冲区写入数据
        void push(const char *data, size_t len)
        {
            ensureEnoughSize(len);
            std::copy(data, data + len, &_buffer[_writer_idx]);
            moveWriter(len);
        }

        // 返回可读数据的骑士地址
        const char *begin()
        {
            return &_buffer[_reader_idx];
        }

        // 获取可读数据长度
        size_t readAbleSize()
        {
            return _writer_idx - _reader_idx;
        }
        
        // 获取剩余可写数据长度
        size_t wirteAbleSize() 
        {
            return _buffer.size() - _writer_idx;
        }

        // 对读写指针进行向后偏移操作
        void moveReader(size_t len)
        {
            assert(len <= readAbleSize());
            _reader_idx += len;
        }

        // 重置读写位置，初始化缓冲区
        void reset()
        {
            _reader_idx = 0;
            _writer_idx = 0;
        }

        // 交换buffer
        void swap(Buffer &buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_reader_idx, buffer._reader_idx);
            std::swap(_writer_idx, buffer._writer_idx);
        }

        // 判断缓冲区是否为空
        bool empty()
        {
            return _reader_idx == _writer_idx;
        }

    private:
        // 对写指针进行向后偏移操作
        void moveWriter(size_t len)
        {
            assert(len + _writer_idx <= _buffer.size());
            _writer_idx += len;
        }
        
        // 空间扩容
        void ensureEnoughSize(size_t len) 
        {
            if (len < wirteAbleSize())  return;
            size_t new_size = 0;
            if (_buffer.size() < THRESHOLD_BUFFER_SIZE)
                new_size = _buffer.size() * 2 < len ? _buffer.size() * 2 + len : _buffer.size() * 2;
            else
                new_size = (_buffer.size() + INCREMENT_BUFFER_SIZE) < len ? 
                        (_buffer.size() + INCREMENT_BUFFER_SIZE + len) 
                        : (_buffer.size() + INCREMENT_BUFFER_SIZE);
            _buffer.resize(new_size);    
        }
    private:
        std::vector<char> _buffer;
        size_t _reader_idx; // 当前可读数据起始位置
        size_t _writer_idx; // 当前可写数据起始位置
    };
}

#endif